<template>
  <el-dialog
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    custom-class="dialogWrapper"
    :before-close="closeDialog">
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
      <el-form-item label="图片序号" prop="serialNumber" required>
        <el-input v-model.trim="formData.serialNumber" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="img">
      	<div class="editImg" v-if="imgShow === 'edit'">
      		<img :src="imgSrc(formData.picUrl)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  list-type="picture-card"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg"
				  :auto-upload = "false"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				   <div slot="tip" class="el-upload__tip">建议尺寸：760*440</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
     </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')" :disabled="Subabled">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import { md5 } from '@/utilities/crypto' // 加密
import editorImage from "@/components/Tinymce/components/editorImage";
var serialize = require('form-serialize');
export default {
  name: "edit-role",
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }
    return {
      menus: [],
      list: [],
      institutionNo:"",
      imgShow:"",
      Subabled:false,
      formData: {
        name: "",
        seq: "",
        url: ""
      },
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      menuInfo: [],
      rules: {
        serialNumber: [{ required: true, message: "请输入图片序号", trigger: "blur" },
        { min: 1, max: 11, message: '长度在 11个字符以内', trigger: 'blur' }]
      }
    }
  },
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    closeDialog() {
      this.$emit("close");
    },
    baseUrl(){
    	return "api/console/product/addBanner.do";
    },
    imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
		handleRemove(file, fileList) {
    	console.log(file, fileList);
//  	if(document.getElementsByClassName("el-upload-list__item")[0]){
//  		var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
//	      thisNode.parentNode.removeChild(thisNode);
//  	}
 	  },
    handleChangeImg(file, fileList){
    	this.imgShow = ""
    	if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
	    		var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
	    		thisNode.parentNode.removeChild(thisNode);
	    	}
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    submit(formName) {
    	this.Subabled = true;
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
            	//把图片的信息和参数放进请求头里
            	this.getFromData({
            		productNo:this.productNo,
				        serialNumber: this.formData.serialNumber
				      },"/ecshop/console/product/addBanner.do");
	          } 
            else {
              this.getFromData({
				    		id: this.formData.id,
				    		productNo:this.formData.productNo,
				        serialNumber: this.formData.serialNumber
				      },"/ecshop/console/product/updateBanner.do");
            }
            this.dialogFormVisible = false;
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    },
    signature(data) {
		  return md5(data)
		},
		getFromData(dataObj,setUrl){
			let formData = new FormData();
			let data = dataObj
    	let token = sessionStorage.getItem('token');
    	let  a = new Date();
			let btime= a .getTime();
			var signs = "data="+JSON.stringify(data)+"&stmb="+btime;
    	formData.append("bannerImg", document.getElementsByClassName("el-upload__input")[0].files[0]);
    	formData.append("data", JSON.stringify(data));
    	formData.append("version", "");
    	formData.append("token", token);
    	formData.append("stmb", btime);
    	formData.append('sign', this.signature(signs))
			var oReq = new XMLHttpRequest();
			oReq.open("POST", setUrl, true);
			oReq.send(formData);
			oReq.onreadystatechange = () => {//在这里指定上传成功的回调函数，接受返回值  
            if (oReq.readyState == 4 && oReq.status == 200) {  
                let res = JSON.parse(oReq.responseText);  
//              console.log(typeof(res))
//              console.log(res.rspCode)
                if(res.rspCode){
                	if(res.rspCode == "0000"){
                	this.$message({
			              showClose: true,
			              message: "提交成功",
			              type: "success"
			            });
			            this.Subabled = false;
			            this.$emit("close", true);
	                }else if(res.rspCode == "1111"){
	                	this.$message({
				              showClose: true,
				              message: "服务器异常，请联系管理员或稍后再试!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "1998"){
	                	this.$message({
				              showClose: true,
				              message: "参数非法!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "1999"){
	                	this.$message({
				              showClose: true,
				              message: "会话超时!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "3333"){
	                	this.$message({
				              showClose: true,
				              message: "参数缺失!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "4444"){
	                	this.$message({
				              showClose: true,
				              message: "请求不合理!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "4000"){
	                	this.$message({
				              showClose: true,
				              message: "上传的文件不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5000"){
	                	this.$message({
				              showClose: true,
				              message: "token失效，需要重新登入!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5001"){
	                	this.$message({
				              showClose: true,
				              message: "没有权限!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5002"){
	                	this.$message({
				              showClose: true,
				              message: "角色已经存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5003"){
	                	this.$message({
				              showClose: true,
				              message: "角色已经使用!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5203"){
	                	this.$message({
				              showClose: true,
				              message: "查询出来的数据过大，无法导出!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5004"){
	                	this.$message({
				              showClose: true,
				              message: "用户锁定!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5005"){
	                	this.$message({
				              showClose: true,
				              message: "菜单不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5006"){
	                	this.$message({
				              showClose: true,
				              message: "用户密码错误!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5007"){
	                	this.$message({
				              showClose: true,
				              message: "用户名已存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5007"){
	                	this.$message({
				              showClose: true,
				              message: "用户名已存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5008"){
	                	this.$message({
				              showClose: true,
				              message: "菜单添加失败!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5009"){
	                	this.$message({
				              showClose: true,
				              message: "权限失败!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5010"){
	                	this.$message({
				              showClose: true,
				              message: "输入的原密码错误!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "5011"){
	                	this.$message({
				              showClose: true,
				              message: "输入的权限菜单为空!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6001"){
	                	this.$message({
				              showClose: true,
				              message: "商品信息不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6002"){
	                	this.$message({
				              showClose: true,
				              message: "商品不是实物!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6003"){
	                	this.$message({
				              showClose: true,
				              message: "商品名称已经存在了!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6004"){
	                	this.$message({
				              showClose: true,
				              message: "上传的文件不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6005"){
	                	this.$message({
				              showClose: true,
				              message: "上传的文件数量错误!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6006"){
	                	this.$message({
				              showClose: true,
				              message: "上传的文件xls不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6007"){
	                	this.$message({
				              showClose: true,
				              message: "商品库存还有可用数量!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6008"){
	                	this.$message({
				              showClose: true,
				              message: "商品库存没有可用数量!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6101"){
	                	this.$message({
				              showClose: true,
				              message: "机构名称已经存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6102"){
	                	this.$message({
				              showClose: true,
				              message: "上传的图片不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6103"){
	                	this.$message({
				              showClose: true,
				              message: "banner名称已经存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6104"){
	                	this.$message({
				              showClose: true,
				              message: "上传的图片不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6201"){
	                	this.$message({
				              showClose: true,
				              message: "查询的信息无效!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6301"){
	                	this.$message({
				              showClose: true,
				              message: "商户名称已经存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6302"){
	                	this.$message({
				              showClose: true,
				              message: "商户用户名称已经存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }else if(res.rspCode == "6303"){
	                	this.$message({
				              showClose: true,
				              message: "商户信息不存在!",
				              type: "error"
				            });
				            this.Subabled = false;
	                }
                }
            }
        };
		}
  },
  mounted() {},
  components: {
      'editorImage': editorImage
    }
};
</script>
<style>
.dialogWrapper {
  width: 540px;
}
.el-select {
  width: 100%;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
</style>
